/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package proxy;

import client.Exception.ExceptionServidorNaoEncontrado;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Observable;

/**
 *
 * @author root
 */
public class Cliente_IRC extends Observable implements Runnable, ISocketPeer {

    private Socket socket;
    private String host;
    private int porta = 6667;
    private boolean run;
    private BufferedWriter out;
    private BufferedReader in;
    private EscritorSocket escritor;

    public Cliente_IRC(String host, int porta) {
        this.host = host;
        this.porta = porta;
        escritor = new EscritorSocket(this);
    }

    public Cliente_IRC(String host) {
        this.host = host;
        escritor = new EscritorSocket(this);
    }

    public void stop() {
        this.run = false;
        try {
            in.close();
            out.close();
            socket.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void escreverLinha(String linha) {
        escritor.escreverLinha(linha);
    }

    public void run() {
        try {
            this.socket = new Socket(host, porta);
            if (socket.isConnected()) {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

                Thread t = new Thread(escritor);
                t.start();
                setChanged();
                notifyObservers(Boolean.TRUE);

                this.run = true;
                while (run) {
                    String leitura = in.readLine();
                    setChanged();
                    notifyObservers(leitura);
                }
            }

            setChanged();
            notifyObservers(Boolean.FALSE);

        } catch (Exception e) {
            new ExceptionServidorNaoEncontrado(e);
        }

    }

    public BufferedWriter getBuffWriter() {
        return this.out;
    }

    public BufferedReader getBuffReader() {
        return this.in;
    }

    public Socket getSocket() {
        return this.socket;
    }

    public boolean isConectado() {
        return socket.isConnected();
    }
}
